<template>
	<view>

		<view v-if="isLoading" class="loading-container">
			<text>加载中...</text>
		</view>

		<view class="form-container">
			<view v-for="(item, index) in formConfig" :key="index">
				<template v-if="item.display === 'true'">
					<!-- 表格组件 -->
					<view v-if="item.type === 'master'" class="form-item">
						<text class="form-label">{{item.label}}</text>
						<!-- 						<button class="add-btn" @click="addTableRow(item)">+</button> -->
						<uni-table ref="table" border stripe emptyText="暂无更多数据">
							<uni-tr>
								<uni-th align="center" v-for="(col,i) in item.masterForm.columns"
									:key="i">{{col.value}}</uni-th>
								<uni-th align="center">操作</uni-th>
							</uni-tr>
							<uni-tr v-for="(itemTable, rowIndex) in formData[item.value]" :key="rowIndex">
								<uni-td align="center" v-for="(col, colIndex) in item.masterForm.columns"
									:key="colIndex">
									<template v-if="col.display === 'true'">
										{{itemTable[col.key] || '-'}}
									</template>
									<template v-else>
										<view v-if="col.type==='input'">
											<input v-model="itemTable[col.key]" :placeholder='"请输入" + col.value' />
										</view>
										<view v-if="col.type==='select'">
											<picker @change="(e) => handleSelectTableChange(e, item,itemTable, col.key)"
												:value="getSelectedTableIndex(itemTable[col.key], col.selectOptions)"
												:range="col.selectOptions" range-key="label">
												<view class="picker">
													{{getSelectedTableLabel(itemTable[col.key], col.selectOptions) || '请选择'+ col.value }}
												</view>
											</picker>
										</view>
										<view v-if="col.type==='dialog'">
											<input v-model="itemTable[col.key]" @click="clickTableForm(col,itemTable)"
												:placeholder="'请点击选择'+ col.value" />
										</view>
									</template>
								</uni-td>
								<uni-td align="center">
									<button @click="deleteTableRow(item, rowIndex)" size="mini" type="warn">删除</button>
								</uni-td>
							</uni-tr>
						</uni-table>
						<view class="button-group">
							<button @click="addTableRow(item)">新增行</button>
						</view>
					</view>
					<!-- 输入框 -->
					<view v-if="item.type === 'input'" class="form-item">
						<text class="form-label"
							:style="{color: isValidColor(item.colors) ? item.colors : 'black'}">{{item.label}}</text>
						<input v-model="formData[item.value]" :disabled="item.readOnly === 'true'"
							:placeholder="'请输入'+item.label" class="form-input" />
					</view>

					<!-- 多行文本框 -->
					<view v-if="item.type === 'textarea'" class="form-item">
						<text class="form-label">{{item.label}}</text>
						<textarea v-model="formData[item.value]" auto-height :placeholder="'请输入'+item.label" />
						<view class="divider"></view>
					</view>

					<!-- 弹窗选择 -->
					<view v-if="item.type === 'dialog'" class="form-item">
					  <text class="form-label">{{item.label}}</text>
					  <view class="input-wrapper">
						<input v-model="formData[item.value]"  :disabled="item.readOnly === 'true'" :placeholder="'请点击选择'+item.label"  @click="clickForm(item)" class="form-input"/>
						<uni-icons class="icon-right"  type="search"  size="30"  @click="clickForm(item)"/>
					  </view>
					</view>

					<!-- 下拉选择 -->
					<view v-if="item.type === 'select'" class="form-item">
						<text class="form-label">{{item.label}}</text>
						<picker @change="(e) => handleSelectChange(e, item.value)" :value="selectIndex[item.value]"
							@touchstart="handleTouchStart(item)" :range="getSelectOptions(item)" range-key="label"
							:disabled="item.readOnly === 'true'">
							<view class="picker">
								{{getSelectedLabel(item) || '请选择'+item.label + formData[item.value] }}
							</view>
						</picker>
					</view>

					<!-- 单选框 -->
					<view v-if="item.type === 'radiobox'" class="form-item">
						<text class="form-label">{{item.label}}</text>
						<radio-group @change="(e) => handleRadioChange(e, item.value)">
							<label v-for="(option, i) in getRadioOptions(item)" :key="i" class="radio-label">
								<radio :value="option.value" :checked="formData[item.value] === option.value"
									:disabled="item.readOnly === 'true'" />
								{{option.label}}
							</label>
						</radio-group>
					</view>

					<!-- 开关 -->
					<view v-if="item.type === 'switch'" class="form-item">
						<text class="form-label">{{item.label}}</text>
						<switch :checked="formData[item.value] == 1" @change="(e) => handleSwitchChange(e, item.value)">
						</switch>
					</view>

					<!-- 多选框组件 -->
					<view v-if="item.type === 'checkbox'" class="form-item">
						<text class="form-label">{{item.label}}</text>
						<checkbox-group @change="(e) => handleCheckboxChange(e, item.value)">
							<label v-for="(option, i) in getCheckboxOptions(item)" :key="i">
								<checkbox :value="option.value" :checked="isCheckedBox(item.value, option.value)" />
								{{option.label}}
							</label>
						</checkbox-group>
					</view>

					<!-- 日期选择 -->
					<view v-if="item.type === 'dateselect'" class="form-item">
						<text class="form-label">{{item.label}}</text>
						<picker mode="date" :value="formData[item.value]"
							@change="(e) => handleDateChange(e, item.value)" :disabled="item.readOnly === 'true'">
							<view class="picker">
								{{formData[item.value] || '请选择'+item.label}}
							</view>
						</picker>
					</view>

					<!-- 图片上传组件 -->

					<view v-if="item.type === 'images'" class="form-item">
						<text class="form-label">{{item.label}}</text>
						<view class="upload-container">
							<view class="preview-images">
								<view v-for="(img, imgIndex) in formData[item.value]" :key="imgIndex"
									class="image-item">

									<image :src="`https://${BASE_URL.apiUrl}` + img " mode="aspectFill"
										class="preview-image"></image>

									<!-- 									<image :src="img" mode="aspectFill" class="preview-image"></image> -->
									<view class="delete-btn" @click="removeImage(item.value, imgIndex)">×</view>
								</view>
								<view v-if="formData[item.value].length < 9" class="upload-btn"
									@click="chooseImage(item.value)">
									<text>+</text>
								</view>
							</view>
						</view>
					</view>


				</template>
			</view>
			<button @click="submitForm">提交</button>
		</view>
	</view>
</template>

<script>
	import fileService from "@/api/file/fileService"
	import configService from '@/api/sys/configService.js'
	import BASE_URL from '@/config.js'
	export default {
		data() {
			return {
				id: "",
				dialog: "",
				method: "",
				dataRes: "",
				configID: "",
				isLoading: true,
				checked: false,
				copyTableData: {},
				formConfig: [],
				formData: {},
				selectIndex: {},
				BASE_URL
			}
		},
		created() {},
		onLoad() {
			// this.fetchFormConfig()
			const eventChannel = this.getOpenerEventChannel();
			new Promise((resolve, reject) => {
				eventChannel.on('sendData', (data) => {
					uni.setNavigationBarTitle({
						title: data.dataRes.sTypeName
					});
					this.id = data.dataItem?.id;
					this.method = data.method;
					this.configID = data.palletCaption;
					this.dataRes = data.dataRes
					resolve();
				}, (err) => {
					reject(err);
				});
			}).then(() => {
				this.fetchFormConfig()
			}).catch((err) => {
				// 数据接收失败的处理
			});
		},
		methods: {
			fetchFormConfig() {
				this.mockApiRequest()
			},
			async mockApiRequest() {
				// TODO: 2025/7/9  新增初始化
				try {
					const res = await configService.getFormConfig(this.configID, this.id);
					this.formConfig = res;
					// this.formConfig = [{
					// 		label: "订单",
					// 		value: "orderNo",
					// 		type: "input",
					// 		display: "true",
					// 		readOnly: "false"
					// 	},
					// 	{
					// 		label: "多行",
					// 		value: "textarea",
					// 		type: "textarea",
					// 		display: "true",
					// 		readOnly: "false"
					// 	},
					// 	{
					// 		label: "款号",
					// 		value: "style", //注意: value(style)值一定要在tableData(style)中存在
					// 		type: "dialog",
					// 		display: "true",
					// 		readOnly: "false",
					// 		dialogForm: { //dialogForm 固定的 
					// 			columns: [{
					// 					key: "order",
					// 					value: "订单号"
					// 				},
					// 				{
					// 					key: "style",
					// 					value: "款号"
					// 				}
					// 			],
					// 			tableData: [{
					// 				order: "21570921",
					// 				style: "2970956271"
					// 			}]
					// 		}
					// 	},
					// 	{
					// 		label: "订单类型",
					// 		value: "orderType",
					// 		type: "select",
					// 		display: "true",
					// 		readOnly: "false",
					// 		selectOptions: { //selectOptions固定的 中 orderType 一定要与value中的值一样
					// 			orderType: [{
					// 					label: "普通订单",
					// 					value: "1",
					// 				},
					// 				{
					// 					label: "VIP订单",
					// 					value: "2",
					// 				},
					// 				{
					// 					label: "批发订单",
					// 					value: "3",
					// 				}
					// 			]
					// 		}
					// 	},
					// 	{
					// 		label: "单选框",
					// 		value: "open",
					// 		type: "radiobox",
					// 		display: "true",
					// 		readOnly: "false",
					// 		radioOptions: { // 单选框选项
					// 			open: [{
					// 					label: "开启",
					// 					value: "1",
					// 				},
					// 				{
					// 					label: "关闭",
					// 					value: "2",
					// 				}
					// 			]
					// 		},
					// 	},
					// 	{
					// 		label: "开关",
					// 		value: "switch",
					// 		type: "switch",
					// 		display: "true",
					// 		readOnly: "false"
					// 	},
					// 	{
					// 		label: "类别",
					// 		value: "category",
					// 		type: "checkbox",
					// 		display: "true",
					// 		readOnly: "false",
					// 		checkboxOptions: { // 多选框
					// 			category: [{
					// 					label: "普通订单",
					// 					value: "1"
					// 				},
					// 				{
					// 					label: "加急订单",
					// 					value: "2"
					// 				},
					// 				{
					// 					label: "特殊订单",
					// 					value: "3"
					// 				}
					// 			]
					// 		},
					// 	},
					// 	{
					// 		label: "订单时间",
					// 		value: "orderTime",
					// 		type: "dateselect",
					// 		display: "true",
					// 		readOnly: "false"
					// 	},
					// 	{
					// 		label: "图片上传",
					// 		value: "imgurl",
					// 		type: "images",
					// 		display: "true",
					// 		readOnly: "false"
					// 	},

					// 	{
					// 		label: "主附表",
					// 		value: "styleTable",
					// 		type: "master", //固定的master
					// 		display: "true",
					// 		readOnly: "false",
					// 		masterForm: { // masterForm固定的
					// 			columns: [{
					// 					key: "order",
					// 					value: "订单号",
					// 					display: "false",
					// 					type: "input",
					// 				},
					// 				{
					// 					key: "style",
					// 					value: "款号",
					// 					display: "false",
					// 					type: "dialog",
					// 					dialogForm: {
					// 						columns: [{
					// 								key: "order",
					// 								value: "订单号",
					// 								existence: "false"
					// 							},
					// 							{
					// 								key: "style",
					// 								value: "款号",
					// 								existence: "true"
					// 							}
					// 						],
					// 						tableData: [{
					// 							order: "21570921",
					// 							style: "2970956271"
					// 						}]
					// 					}
					// 				},
					// 				{
					// 					key: "orderType",
					// 					value: "订单类型",
					// 					display: "false",
					// 					type: "select",
					// 					selectOptions: [{
					// 							label: "普通订单",
					// 							value: "1",
					// 						},
					// 						{
					// 							label: "VIP订单",
					// 							value: "2",
					// 						},
					// 						{
					// 							label: "批发订单",
					// 							value: "3",
					// 						}
					// 					]
					// 				}
					// 			],
					// 		}
					// 	},

					// ];
					//TODO: 2025/7/9初始化
					this.initFormData();
				} catch (error) {
					this.isLoading = false;
					console.error('获取表单配置失败:', error);
				}
			},
			initFormData() {
				this.formConfig.forEach(item => {
					let initValue = ''
					if (item.type === 'images' || item.type === 'master') {
						initValue = [] // 图片上传需要数组
					} else {
						initValue = '' // 其他类型默认字符串
					}
					this.$set(this.formData, item.value, initValue)
					if (item.type === 'select') {
						this.$set(this.selectIndex, item.value, 0)
					}
				});
				if (this.method === "edit") {
					this.editFormData();
				} else {
					this.isLoading = false;
				}
			},
			async editFormData() {
				// 模拟查询出的数据
				// const fetchedData = {
				// 	"orderNo": "21570921",
				// 	"style": "2970956271",
				// 	"orderType": "1",
				// 	"open": "1",
				// 	"switch": "1",
				// 	"category": "1,3",
				// 	"orderTime": "2025-07-09",
				// 	"imgurl": [
				// 		"/file/download?uploadPath=userdir/2025/7&name=848c09d0-0189-418f-a2ff-6b9755500f48.jpg&oldName=c2be8d0a2fddaf6b0c63ddb8a64ac810.jpg"
				// 	]
				//};
				const fetchedData = await configService.getById(this.configID, this.id);
				this.formConfig.forEach(item => {
					if (fetchedData.hasOwnProperty(item.value)) {
						if (item.type === 'images') {
							// 对于图片上传组件，直接赋值图片数组
							const arrayImg = fetchedData[item.value].split(',')
							this.$set(this.formData, item.value, arrayImg);
						} else if (item.type === 'checkbox') {
							// 对于多选框组件，需要将字符串转换为数组
							this.$set(this.formData, item.value, fetchedData[item.value].split(','));
						} else {
							// 对于其他类型的组件，直接赋值
							this.$set(this.formData, item.value, fetchedData[item.value]);
						}
					} else {
						// 对于没有在查询数据中定义的字段，设置一个初始值（空字符串或空数组）
						this.$set(this.formData, item.value, item.type === 'images' ? [] : '');
					}
					// 对于下拉选择框，需要额外设置selectIndex
					if (item.type === 'select') {
						// 这里假设selectOptions的value字段和fetchedData中的值是一一对应的
						// 实际情况下可能需要根据具体情况进行调整
						const options = this.getSelectOptions(item);
						const selectedIndex = options.findIndex(opt => opt.value === fetchedData[item.value]);
						this.$set(this.selectIndex, item.value, selectedIndex !== -1 ? selectedIndex : 0);
					}
				});
				this.isLoading = false;
			},
			//校验colors 是否合法
			isValidColor(color) {
				if (!color) return false;
				const colorKeywords = ['red', 'green', 'blue', 'black', 'white', /*...*/ ];
				if (colorKeywords.includes(color.toLowerCase())) return true;
				const hexRegex = /^#([0-9A-F]{3}){1,2}$/i;
				if (hexRegex.test(color)) return true;
				const rgbRegex = /^rgba?$(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*(\d*(?:\.\d+)?))?$$/i;
				return rgbRegex.test(color);
			},
			getSelectOptions(item) {
				return item.selectOptions?.[item.value] || []
			},
			getCheckboxOptions(item) {
				return item.checkboxOptions?.[item.value] || []
			},
			getRadioOptions(item) {
				return item.radioOptions?.[item.value] || []
			},
			isCheckedBox(field, value) {
				return (this.formData[field] || []).includes(value);
			},
			getSelectedLabel(item) {
				const options = this.getSelectOptions(item)
				const selected = options.find(opt =>
					opt.value === this.formData[item.value]
				)
				return selected?.label || ''
			},
			handleSelectChange(e, field) {
				const item = this.formConfig.find(i => i.value === field)
				const options = this.getSelectOptions(item)
				this.selectIndex[field] = e.detail.value
				this.formData[field] = options[e.detail.value]?.value || ''
			},
			async handleTouchStart(item) {
				const newOptions = await configService.getClickSelectConfig(this.formData, this.configID, item.value);
				this.setSelectOptions(item, newOptions);
			},
			setSelectOptions(item, options) {
				// 更新数据
				this.$set(item.selectOptions, item.value, options);
			},
			handleCheckboxChange(e, field) {
				this.formData[field] = e.detail.value.join(',')
			},
			handleRadioChange(e, field) {
				this.formData[field] = e.detail.value
			},
			handleSwitchChange(e, field) {
				this.formData[field] = e.detail.value ? 1 : 0;
			},
			handleDateChange(e, field) {
				this.formData[field] = e.detail.value
			},
			//处理表格中的下拉组件
			handleSelectTableChange(e, item, itemTable, field) {
				const value = e.detail.value;
				const options = item.masterForm.columns.find(col => col.key === field).selectOptions;
				itemTable[field] = options[value].value;
			},
			getSelectedTableLabel(value, options) {
				if (!value) return '';
				const option = options.find(opt => opt.value === value);
				return option ? option.label : '';
			},
			getSelectedTableIndex(value, options) {
				if (!value) return 0;
				const index = options.findIndex(opt => opt.value === value);
				return index >= 0 ? index : 0;
			},
			//处理表格中弹出组件
			clickTableForm(col, item) {
				this.copyTableData = item;
				uni.navigateTo({
					url: "/pages/subA/sys/appConfigure/appConfigDialog",
					events: {
						acceptFormData: this.handlAcceptTableFormData
					},
					success: (res) => {
						res.eventChannel.emit('sendData', col);
					}
				});
			},
			handlAcceptTableFormData(data) {
				for (let col of data.columns) {
					if (col.existence === 'true') {
						this.copyTableData[col.key] = data.item[col.key] || ''
					}
				}
			},
			//表格组件新增行方法
			addTableRow(item) {
				this.formData[item.value].push(item.masterForm.columns.reduce((acc, {
					key
				}) => ({
					...acc,
					[key]: ''
				}), {}));
			},
			//表格组件删除行方法
			deleteTableRow(item, rowIndex) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这一行吗？',
					success: (res) => {
						if (res.confirm) {
							this.formData[item.value].splice(rowIndex, 1);
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}
					}
				});
			},
			//点击选择图片
			chooseImage(field) {
				if (this.formConfig.find(i => i.value === field).readOnly === 'true') return
				uni.chooseImage({
					count: 9 - this.formData[field].length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.uploadImg(res.tempFilePaths[0], field)
					}
				})
			},
			//删除图片
			removeImage(field, index) {
				if (this.formConfig.find(i => i.value === field).readOnly === 'true') return
				const newImages = [...this.formData[field]]
				newImages.splice(index, 1)
				this.$set(this.formData, field, newImages)
			},
			//上传图片
			uploadImg(img, field) {
				fileService.upload(img).then((res) => {
					this.formData[field].push(res)
				})
			},
			//点击弹框选择
			clickForm(item) {
				uni.navigateTo({
					url: "/pages/subA/sys/appConfigure/appConfigDialog",
					events: {
						acceptFormData: this.handlAcceptFormData
					},
					success: (res) => {
						res.eventChannel.emit('sendData', item);
					}
				});
			},
			//点击弹窗选择回调函数
			handlAcceptFormData(data) {
				for (let col of data.columns) {
					if (col.existence === 'true') {
						this.formData[col.key] = data.item[col.key] || ''
					}
				}
			},
			submitForm() {
				// console.log('提交数据:', this.formData)
				// uni.showModal({
				// 	title: '数据信息',
				// 	content: JSON.stringify(this.formData, null, 2), // 2表示缩进空格数
				// 	showCancel: false
				// });
				uni.showLoading();
				configService.saveConfig(this.formData, this.configID)
					.then((data) => {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						});
						setTimeout(() => uni.navigateTo({
							url: "/pages/subA/sys/appConfigure/appConfigure",
							success: (res) => {
								res.eventChannel.emit('sendData', this.dataRes);
							}
						}), 300);
					})
					.catch((error) => {
						console.error('提交失败', error)
						uni.showToast({
							title: '提交失败',
							icon: 'none'
						})
					})
			}
		}
	}
</script>

<style>
	.form-container {
		padding: 20px;
	}

	.form-item {
		margin-bottom: 20px;
	}

	/* .form-label {
		display: block;
		margin-bottom: 8px;
		font-size: 16px;
		color: #333;
	} */

	.form-input,
	.picker {
		width: 100%;
		height: 40px;
		line-height: 40px;
		padding: 0 10px;
		border: 1px solid #ddd;
		border-radius: 4px;
	}

	.radio-label {
		margin-right: 15px;
	}

	.upload-container {
		margin-top: 10px;
	}

	.preview-images {
		display: flex;
		flex-wrap: wrap;
	}

	.image-item {
		position: relative;
		width: 80px;
		height: 80px;
		margin-right: 10px;
		margin-bottom: 10px;
	}

	.preview-image {
		width: 100%;
		height: 100%;
		border-radius: 4px;
	}

	.delete-btn {
		position: absolute;
		top: -8px;
		right: -8px;
		width: 20px;
		height: 20px;
		background: #ff4d4f;
		color: white;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 12px;
	}

	.upload-btn {
		width: 80px;
		height: 80px;
		border: 1px dashed #d9d9d9;
		border-radius: 4px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24px;
		color: #999;
	}

	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		font-size: 18px;
		color: #999;
	}

	.form-label {
		display: inline-block;
		margin-bottom: 8px;
		font-size: 16px;
		color: #333;
		vertical-align: middle;
	}

	.add-btn {
		display: inline-block;
		width: 28px;
		height: 28px;
		line-height: 28px;
		margin-left: 10px;
		padding: 0;
		border-radius: 50%;
		background-color: #1890ff;
		color: white;
		font-size: 18px;
		vertical-align: middle;
	}

	.add-btn:active {
		background-color: #096dd9;
	}

	.divider {
		height: 1rpx;
		background-color: #e4e7ed;
		margin: 20rpx 0;
		/* 可选扩展样式 */
		/* width: 80%; */
		/* border-bottom: 1px dashed #999; */
	}
	
	.input-wrapper {
	  position: relative;
	  width: 100%;
	}
	.form-input {
	  padding-right: 40px; /* 留出图标空间 */
	}
	.icon-right {
	  position: absolute;
	  right: 10px;
	  top: 50%;
	  transform: translateY(-50%);
	  cursor: pointer;
	}
</style>